"use strict";

/** @type {string | undefined} */
let lastStage;
/**
 * @template {typeof import('@rspack/core').ProgressPlugin | typeof import('webpack').ProgressPlugin} T
 * @param {T} ProgressPlugin
 * @returns {import('@rspack/core').WebpackPluginInstance}
 */
function WrapperProgressivePlugin(ProgressPlugin) {
  return new ProgressPlugin((percentage, stage, ...args) => {
    const now = new Date();
    const formatNow = `\u001B[32m[${(percentage * 100).toFixed(3)}][${now.getHours()}:${now.getMinutes().toString().padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}.${now.getMilliseconds().toString().padStart(3, "0")}]\u001B[0m`;
    // e.g. Output each progress message directly to the console:
    console.info(
      formatNow,
      stage,
      args[0] || "",
      args[1] ? "|" : "",
      args[1]
        ?.split(/!/)
        .at(-1)
        // eslint-disable-next-line n/no-path-concat
        ?.replace(new RegExp(`/${__dirname}/g`), "@/") || "",
    );

    /// onChangeStage, computedTimer
    if (lastStage === undefined) {
      // firstStage
      // - read reference
      console.time(`--- ${stage} ---`);
      // - write
      lastStage = stage;
    } else if (lastStage !== stage) {
      // - read reference
      console.timeEnd(`--- ${lastStage} ---`);
      console.time(`--- ${stage} ---`);
      // - write
      lastStage = stage;
    }
  });
}

module.exports = { WrapperProgressivePlugin };
